var firstQuery = true;
var orderSize = -1;
var gridColumns_sm=NumberColumn_create();

var proxyManager_columns=[NumberColumn_create(),{
	dataIndex: "inlayDiamondId",
	hideable:false,
    hidden:true
}, {
    header: "钻托名称",
    align : 'center',
    width : 70,
    dataIndex: "name"
}, {
    header: "钻托编号",
    align : 'center',
    width : 75,
    dataIndex: "inlayBatch"
},  {
    header: "镶钻编号",
    align : 'center',
    width : 75,
    dataIndex: "inlayDiaBatch"
}, {
    header: "类型",
    align : 'center',
    width : 50,
    dataIndex: "type"
}, {
    header: "材质",
    align : 'center',
    width : 50,
    dataIndex: "material"
}, {
    header: "价格",
    align : 'center',
    width : 50,
    dataIndex: "midPrice"
}, {
    header: "手寸",
    align : 'center',
    width : 50,
    dataIndex: "hand"
}, {
    header: "刻字",
    align : 'center',
    width : 60,
    dataIndex: "text"
}, {
    header: "工厂编号",
    align : 'center',
    width : 75,
    dataIndex: "inlayFactoryBatch"
}, {
    header: "钻托所属",
    align : 'center',
    width : 60,
    dataIndex: "cmpName"
},{
    header: "操作状态",
    align : 'center',
    width : 60,
    dataIndex: "state",
    renderer:function(v,meta,record){
    	var value="",color="";
    	optStateStore.each(function(rd){
    		value=rd.get('value')==v?rd.get('name'):value;
    		color=rd.get('value')==v?rd.get('color'):color;
    	})
    	return "<font color='"+color+"'>"+value+"</font>";;
    },
  editor:new Ext.form.ComboBox({
		store:optStateStore,
		editable : false,
		mode:"local",
		triggerAction : 'all',
		displayField : 'name',
		valueField : 'value'
    })
},{
    header: "付款状态",
    align : 'center',
    width : 60,
    dataIndex: "payState",
    renderer:function(v,meta,record){
    	var value="",color="";
    	payStateStore.each(function(rd){
    		value=rd.get('value')==v?rd.get('name'):value;
    		color=rd.get('value')==v?rd.get('color'):color;
    	})
    	return "<font color='"+color+"'>"+value+"</font>";;
    },
  editor:new Ext.form.ComboBox({
		store:payStateStore,
		editable : false,
		mode:"local",
		triggerAction : 'all',
		displayField : 'name',
		valueField : 'value'
    })
},{
    header: "发货状态",
    align : 'center',
    width : 60,
    dataIndex: "deliverGoodsState",
    renderer:function(v,meta,record){
    	var value="",color="";
    	deliverGoodsStore.each(function(rd){
    		value=rd.get('value')==v?rd.get('name'):value;
    		color=rd.get('value')==v?rd.get('color'):color;
    	})
    	return "<font color='"+color+"'>"+value+"</font>";;
    },
  editor:new Ext.form.ComboBox({
		store:deliverGoodsStore,
		editable : false,
		mode:"local",
		triggerAction : 'all',
		displayField : 'name',
		valueField : 'value'
    })
}]

//供应商订单明细
var suppGridColumns_sm=NumberColumn_create()
var suppGridColumns=[suppGridColumns_sm,{
    header: "商品编号",
    align : 'center',
    sortable: true,
    resizable: true,
    width : 150,
    dataIndex: "amount"
}, {
    header: "商品数量",
    align : 'center',
    sortable: true,
    resizable: true,
    width : 150,
    dataIndex: "number"
}, {
    header: "商品备注",
    align : 'center',
    sortable: true,
    resizable: true,
    width : 150,
    dataIndex: "remark"
}, {
    header: "操作",
    align : 'center',
    sortable: false,
    resizable: true,
    dataIndex: ""
}];

var gridColumns_sm=NumberColumn_create();
var cm=multiCheckModel_create();
var gridColumns=[gridColumns_sm,cm,{
    dataIndex: "cliOrdMasterId",
	hidden:true,
	hideable:false
},{
    dataIndex: "suppOrdMasterId",
	hidden:true,
	hideable:false
},{
    header: "订单编号",
    align : 'center',
    sortable: true,
    resizable: true,
    width: 150,
    dataIndex: "orderNo"
}, {
//    header: "供应商名称",
//    sortable: true,
//    resizable: true,
//    width: 150,
//    dataIndex: "supplierName"
//}, {
    header: "客户名称",
    align : 'center',
    sortable: true,
    resizable: true,
    width: 150,
    dataIndex: "userName"
}, {
    header: "下单时间",
    align : 'center',
    sortable: true,
    resizable: true,
    width: 150,
    dataIndex: "orderDate"
}, {
    header: "单据总价",
    align : 'center',
    sortable: true,
    resizable: true,
    width: 150,
    dataIndex: "midTotal"
}, {
    header: "单据状态",
    align : 'center',
    sortable: true,
    resizable: true,
    width: 150,
    dataIndex: "orderStatusName",
    renderer : function(value, metaData, record, rowIndex, colIndex, store){
    	if (value == '未处理') {
			return '<B><span style="color:red;">'+value+'</span></B>';
    	} else if (value == '部分处理') {
    		return '<B><span style="color:#FF00CC;">'+value+'</span></B>';
    	} else {
    		return value;
    	}
	} 
}, {
    header: "操作",
    align : 'center',
    sortable: true,
    resizable: true,
    width: 150,
    dataIndex: "data5",
	renderer:function(){
		return '<span style="cursor:pointer;color:blue;">查看明细</span>'
	}
}];

function getFieldsFromColumns(colums){
	var fs=new Array();
	Ext.each(colums,function(col){
		fs.push(col.dataIndex);
	})
	return fs;
}
var gridModel=new Ext.grid.ColumnModel({
  defaultSortable: true,
  defaultWidth: 85,
  columns:gridColumns
})

var gridStore=new Ext.data.JsonStore({
//	fields:getFieldsFromColumns(gridColumns),
//	url:'',
//	autoLoad : false
	
	proxy: new Ext.data.HttpProxy({
        url: 'queryClientOrder.action',
        failure: function(){
            Ext.MessageBox.alert("错误", "数据源获取失败!");
        }
    }),
    totalProperty: 'obj.totalSize',
    successProperty: 'success',
    root: 'obj.returnBolist',
    messageProperty: 'msg',
    fields : getFieldsFromColumns(gridColumns),
	listeners:{
		load:function(store){
			store.each(function(rd){
				rd.data.type=Ext.getCmp("orderType_fl").getValue();
			});
		}
	}
});

var orderGrid = new Ext.grid.GridPanel({
	store: gridStore,
	cm: gridModel,
	sm : cm,
	bbar : new Ext.PagingToolbar({
		pageSize : 20,
		store : gridStore,
		displayInfo:true,
		displyMsg : '显示第{0}条到第{1}条记录，一共{2}条',
		emptyMsg : "没有记录",
		items : [{
			text : '删除',
			style :'float:left',
			handler : function(bt, e) {
				var grid = bt.ownerCt.ownerCt;
				var cm = grid.getSelectionModel();
				var rds = cm.getSelections();
				Ext.Msg.confirm("提示", '你确信要执行删除操作？', function(at, mg) {
					if (at == 'yes') {
						var orderStr = null;
						Ext.each(rds, function(rd) {
							orderStr = (orderStr != null) ? (orderStr + ";" + rd.get('cliOrdMasterId')) : rd.get('cliOrdMasterId');
						})
						var con = new connection({
							url : 'deleteCliOrder.action',
							params : {
								json : orderStr
							},
							success : function(result, response) {
								queryOrder();
								var alt = result.success ? '成功' : '失败';
								Ext.Msg.alert(alt, result.msg);
							},
							failure : function(result, response) {
								queryOrder();
								var alt = result.success ? '成功' : '失败';
								Ext.Msg.alert(alt, result.msg);
							}
						});
						con.submit();
					}
				});
			}
		}]
	}),
	frame: true,
	listeners :{
		cellclick :function(grid, rowIndex,columnIndex,e ){
			var cm = grid.getColumnModel();
			var header = cm.getColumnHeader(columnIndex);
			if (header == '操作') {
				var record = grid.getStore().getAt(rowIndex);
				if (record.data.type == '2') {
					var win = showDealerWindow();
					queryClientOrderDetail(record, win);
				}else if (record.data.type == '1') {
					var win = showSupplierWindow();
					querySuppOrderDetails(record, win);
				}
			}
		}
	}
});

var queryOrderPanel=new Ext.FormPanel({
	layout:'column',
	id : 'queryOrderPanel',
	frame:true,
	regetion:'north',
	defaults:{
		columnWidth:0.17,
		layout:'form',
		labelWidth:55,
		defaults:{
			anchor: '98%'
			}
	},
	items:[{
		items:[{
			fieldLabel:'订单类型',
			id:'orderType_fl',
			store:docTypeStore,
//			value:'2',
			editable : false,
			disabled : true,
			mode:"local",
			triggerAction : 'all',
			displayField : 'name',
			valueField : 'value',
			name : 'orderType',
//			xtype:'combo',
//----------	
			value : '客户订单',
			xtype:'textfield',
			getValue : function() {
				return '2';
			},
//----------			
			listeners:{
				select :function(combo,rd){
					if(rd.get("value")=="1"){
						Ext.getCmp("supplyer_panel_fl").setVisible(true);
						Ext.getCmp("dealer_panel_fl").setVisible(false);
					}else if(rd.get("value")=="2"){
						Ext.getCmp("supplyer_panel_fl").setVisible(false);
						Ext.getCmp("dealer_panel_fl").setVisible(true);
					}
					return true;
				}
			}
		}]
	},{
		columnWidth:0.25,
			xtype:'panel',
			layout:'column',
			defaults:{
				anchor: '90%',
				xtype:'panel',
				layout:'form',
				defaults:{
					xtype:'datefield',
					layout:'form',
					format : 'Y-m-d',
					anchor: '95%'
				}
			},
			items:[{
				columnWidth:0.58,
				items:[{
					fieldLabel:'下单时间',
					name : 'orderDateFrom',
					id : 'orderDateFrom'
				}]
			},{
				columnWidth:0.42,
				labelWidth:10,
				items:[{
					labelSeparator:'-',
					fieldLabel:'-',
					name : 'orderDateTo',
					id : 'orderDateTo'
				}]
			}]
	},{
		defaults:{
			xtype:'panel',
			layout:'form',
			defaults:{
				anchor:'90%',
				xtype:'textfield'
			}
		},
		items: [{
			id:'supplyer_panel_fl',
			labelWidth:70,
			hidden :true,
			items:[{
				fieldLabel: '供应商名称',
				name : 'supplierName',
				id : 'supplierName'
			}]
		},{
			id:'dealer_panel_fl',
			items:[{
				fieldLabel: '客户名称',
				name : 'clientName',
				id : 'clientName'
			}]
		}]
	},{
		items:[{
			xtype:'textfield',
			anchor:'95%',
			fieldLabel:'订单编号', 
			name : 'orderNo',
			id : 'orderNo'
		}]
	},{
		columnWidth:0.1,
		items:[{
			xtype:'button',
			text:'查询',
			id:'searchBt',
			anchor: '40%',
			handler:function(bt, e){
				if (firstQuery) {
					firstQueryOrder();
					firstQuery = false;
				} else {
					queryOrder();
				}
			}
		}]
	}]
});

function queryOrder() {
	var data = panel_gatherData(queryOrderPanel);
	var store = orderGrid.getStore();
	store.baseParams = {
		json : Ext.encode(data)
	};
	Ext.Ajax.request( {
		url : 'queryClientOrder.action',
		params : {
			json : Ext.encode(data)
		},
		success : function(result, request) {
			var data = Ext.util.JSON.decode(result.responseText);
			var objData = data.obj;
			var store=orderGrid.getStore();
//			store.loadData(objData.returnBolist);
			store.load();
//			alert(Ext.encode(panel_gatherData(queryOrderPanel)));
			if (Ext.encode(panel_gatherData(queryOrderPanel))=='{"orderType":"2","orderDateFrom":"","orderDateTo":"","supplierName":"","clientName":"","orderNo":""}') 
				setTimeout(firstQueryOrder, 10000);
			}
	});
}

function firstQueryOrder() {
	if (firstQuery) {
		var data=panel_gatherData(queryOrderPanel);
		var store=orderGrid.getStore();
		store.baseParams ={json:Ext.encode(data)};
		Ext.Ajax.request( {
			url : 'queryClientOrder.action',
			params : {
				json : Ext.encode(data)
			},
			success : resultAction
		});
	} else {
		var data = '{"orderType":"2","orderDateFrom":"","orderDateTo":"","supplierName":"","clientName":"","orderNo":""}';
		Ext.Ajax.request( {
			url : 'queryClientOrder.action',
			params : {
				json : data
			},
			success : resultAction
		});
	}
}

function resultAction(result, request) {
	var data = Ext.util.JSON.decode(result.responseText);
	var objData = data.obj;
	var currentSize;
	if (!Ext.isEmpty(objData.returnBolist)) {
		currentSize = objData.totalSize;
	}
	
	if (orderSize> -1 && currentSize > orderSize) {
		Ext.Msg.alert('新订单提示','您有新的订单，请及时处理！');
	}
	orderSize = currentSize;
	var store=orderGrid.getStore();
	store.load();
//	store.each(function(rd){
//		rd.data.type=objData.type;
//	});
//	alert(Ext.encode(panel_gatherData(queryOrderPanel)));
	if (Ext.encode(panel_gatherData(queryOrderPanel))=='{"orderType":"2","orderDateFrom":"","orderDateTo":"","supplierName":"","clientName":"","orderNo":""}') 
		setTimeout(firstQueryOrder, 10000);
}

function queryClientOrderDetail(record, win) {
	var con = new connection({
		url : 'queryClientOrderById.action',
		params : {
			json : record.get("cliOrdMasterId")
		},
		success : function(rep, opt) {
			if (rep.success) {
				if (null != rep.obj.clientOrderBo) {
					
					Ext.each(rep.obj.clientOrderDetaillist,function(obj){
						if(Ext.isEmpty(obj.state)){
							obj.state='0';
							obj.stateName=obj.state;
						}
					})
					panel_initData(win, null, rep.obj.clientOrderBo);
				}
				win.showGridData(rep);
			} else {
				alert("******faile********");
			}
		}
	})
	con.submit();
}

function querySuppOrderDetails(record, win) {
	var con = new connection({
		url : 'querySuppOrderById.action',
		params : {
			json : record.get("suppOrdMasterId")
		},
		success : function(rep, opt) {
			if (rep.success) {
				if (null != rep.obj.suppOrderBo) {
					panel_initData(win, null, rep.obj.suppOrderBo);
				}
				win.showGridData(rep);
			} else {
				Ext.Msg.alert('异常',rep.msg);
			}
		},
		failure : function(result, response) {
		    Ext.Msg.alert('异常','系统异常,请联系管理员');
		}
	})
	con.submit();
}

Ext.onReady(function() {
	new Ext.Viewport({
		layout : 'border',
		items : [{
			region : 'north',
			split : true,
			border : false,
			height : 40,
			collapseMode : 'mini',
			layout : 'fit',
			items : [queryOrderPanel]
		}, {
			region : 'center',
			split : true,
			border : false,
			layout : 'fit',
			items : [orderGrid]
		}]
	});
});
	
  